package udpSocket;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Random;

public class layerOneClient {

	private DatagramSocket clientSocket;
	InetAddress host;
	int port; 
	int noiseProb;

	/**
	 * layerOneClient configuration parameters of the server to send the message.
	 * @param host String contain the domain name or IP address of the server, default is localhost. 
	 * @param port Server port number of the server, default is 9876.
	 * @param noiseProb probability of lost messages from client to server
	 *  (Package Lost Rate), default 20%.
	 * @throws Exception
	 */
	public layerOneClient() throws Exception{
		clientSocket = new DatagramSocket();
		this.host = InetAddress.getByName("localhost");
		this.noiseProb  = 20;
		this.port = 9876;
	}
	
	public layerOneClient(String host, int port, int noise) throws Exception{
		clientSocket = new DatagramSocket();
		this.host = InetAddress.getByName(host);
		this.port = port;
		this.noiseProb  = 20; 
	}

	public void clientSend(String message) throws Exception{
		byte[] sendData = new byte[1024];
		String sentence = message;
		sendData = sentence.getBytes();
		DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, host, port);
		if (noise()==false)
			clientSocket.send(sendPacket);
	}

	public String clientReceive() throws Exception,SocketException{
		clientSocket.setSoTimeout(1000);
		byte[] receiveData = new byte[1024];
		DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
		clientSocket.receive(receivePacket);

		return new String(receivePacket.getData());

	}
	
	private boolean noise(){
		Random prob = new Random();
		boolean noise=false;
		int num = prob.nextInt(100/noiseProb);

		if(num==3){
			noise = true;
		}
		return noise;
	}

}
